//
//  SettingTableViewController.m
//  QuickReadComic
//
//  Created by 苗钧豪 on 16/9/18.
//  Copyright © 2016年 苗钧豪. All rights reserved.
//

#import "SettingTableViewController.h"
#import "JHAccountTool.h"
#import "CustomCell2.h"
#import "webViewController.h"
#import "UserViewController.h"
#import "KuaiKanViewController.h"
#import "UMSocial.h"
#import "UMSocialSinaSSOHandler.h"
#import "MineViewController.h"
#import "SDImageCache.h"
@interface SettingTableViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)NSArray *arr1;
@property(nonatomic,strong)NSArray *arr11;
@property(nonatomic,strong)NSArray *arr2;
@property(nonatomic,strong)NSArray *arr3;
@property(nonatomic,strong)UITableView *tableView;
@end

@implementation SettingTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"设置";
    self.view.backgroundColor = [UIColor whiteColor];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 120) style:(UITableViewStylePlain)];
    [_tableView registerNib:[UINib nibWithNibName:@"CustomCell2" bundle:nil] forCellReuseIdentifier:@"cell2"];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"set2"];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"set3"];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.bounces = NO;
    [self.view addSubview:_tableView];
    UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    btn.frame = CGRectMake(10, self.view.bounds.size.height - 100, self.view.bounds.size.width - 20, 50);
    [btn setTitle:@"退出账号" forState:(UIControlStateNormal)];
    [btn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    [btn addTarget:self action:@selector(removeUser) forControlEvents:(UIControlEventTouchUpInside)];
    btn.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:btn];
    self.arr1 = [NSArray arrayWithObjects:@"低流量模式",@"回复推送",@"更新提醒", nil];
    self.arr11 = [NSArray arrayWithObjects:@"非WiFi环境下加载低质量,可为您节省流量70%",@"开启后及时收到别人的评论<(— ▽ —)>",@"关注作品更新后将及时提醒", nil];
    self.arr2 = [NSArray arrayWithObjects:@"赏个好评",@"意见反馈",@"推荐给朋友", nil];
    self.arr3 = [NSArray arrayWithObjects:@"清理缓存",@"关于快看",@"用户协议", nil];
    UIImage *image = [UIImage imageNamed:@"IMG_0425"];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithImage:[image imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] style:(UIBarButtonItemStylePlain) target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = item;
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
// 退出账号
- (void)removeUser {
    NSString *name = @"";
    NSString *pass = @"";
    NSArray *newarray = [NSArray arrayWithObjects:name,pass, nil];
    NSArray *array = [JHAccountTool getAccount];
    array = newarray;
    [JHAccountTool saveAccount:array];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSInteger num = [user integerForKey:@"isLogin"];
    num = 0;
    [user setInteger:num forKey:@"isLogin"];
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 2 && indexPath.row == 0) {
        [[SDImageCache sharedImageCache] clearDisk];
//        NSInteger tmpSize = [[SDImageCache sharedImageCache] getSize];
        [_tableView reloadData];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 40)];
        label.center = self.view.center;
        label.backgroundColor = [UIColor darkGrayColor];
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"清除缓存成功";
        [self.view addSubview:label];
        [UIView animateWithDuration:3 animations:^{
            label.alpha = 0;
        }];
    } else if (indexPath.section == 2 && indexPath.row == 2) {
        UserViewController *vc = [[UserViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    } else if (indexPath.section == 2 && indexPath.row == 1) {
        KuaiKanViewController *vc = [[KuaiKanViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    } else if (indexPath.section == 1 && indexPath.row == 2) {
        [UMSocialConfig setSupportedInterfaceOrientations:UIInterfaceOrientationMaskLandscape];
        [UMSocialData defaultData].extConfig.title = @"看漫画不？带我一个，我这个APP贼强";
        [UMSocialData defaultData].extConfig.sinaData.urlResource.url = @"http://baidu.com";
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"507fcab25270157b37000010"
                                          shareText:@"友盟社会化分享让您快速实现分享等社会化功能，http://umeng.com/social"
                                         shareImage:[UIImage imageNamed:@"UMS_sina_icon"]
                                    shareToSnsNames:@[UMShareToSina,UMShareToQzone]
                                           delegate:nil];
    }
}
- (void)back {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        CustomCell2 *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2" forIndexPath:indexPath];
        cell.nameLabel.text = _arr1[indexPath.row];
        cell.grayLabel.text = _arr11[indexPath.row];
        cell.mySwitch.on = NO;
        if (indexPath.row == 2) {
            [cell.mySwitch addTarget:self action:@selector(switch2:) forControlEvents:(UIControlEventValueChanged)];
        } else if (indexPath.row == 0) {
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            NSInteger num = [user integerForKey:@"isOn"];
            if (num == 0) {
                cell.mySwitch.on = NO;
            } else if (num == 1) {
                cell.mySwitch.on = YES;
            }
            [cell.mySwitch addTarget:self action:@selector(switch0:) forControlEvents:(UIControlEventValueChanged)];
        }
        return cell;
    } else if (indexPath.section == 1) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"set2" forIndexPath:indexPath];
        cell.textLabel.text = _arr2[indexPath.row];
        return cell;
    } else if (indexPath.section == 2) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"set3" forIndexPath:indexPath];
        cell.textLabel.text = _arr3[indexPath.row];
        return cell;
    }
    return nil;
}
#pragma mark ================ switch ================
- (void)switch0:(UISwitch *)mySwitch {
    if ([mySwitch isOn] == YES) {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSInteger num = [user integerForKey:@"isOn"];
        num = 1;
        [user setInteger:num forKey:@"isOn"];
    } else if ([mySwitch isOn] == NO) {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSInteger num = [user integerForKey:@"isOn"];
        num = 0;
        [user setInteger:num forKey:@"isOn"];
    }
}
- (void)switch2:(UISwitch *)mySwitch {
    if ([mySwitch isOn] == YES) {
        UILocalNotification *lacalNotification = [[UILocalNotification alloc]init];
        if (lacalNotification) {
            lacalNotification.timeZone = [NSTimeZone defaultTimeZone];
            NSDate *now = [NSDate date];
            NSLog(@"%@",now);
            NSDate *dateToFire = [now dateByAddingTimeInterval:28805];
            NSLog(@"%@",dateToFire);
//            lacalNotification.fireDate = dateToFire;
            lacalNotification.alertBody = @"开启更新提醒，您关注的内容将在更新时第一时间提醒您";
            lacalNotification.soundName = UILocalNotificationDefaultSoundName;
            lacalNotification.repeatInterval = 5;
            NSDictionary *infoDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
            lacalNotification.userInfo = infoDic;
            lacalNotification.applicationIconBadgeNumber = 1;
            [[UIApplication sharedApplication] scheduleLocalNotification:lacalNotification];
        }
        
    } else {
        [[UIApplication sharedApplication] cancelAllLocalNotifications];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"您即将关闭消息提醒，关闭后您将不能收到消息提醒" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
    }
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
